import React, { useEffect, useState } from 'react';
import useStore from '../../../components/useStore';
import request from '../../../untils/request';

const BomDetail = () => {
    const { collapsed } = useStore();
    const [parentNumber, setParentNumber] = useState(null);
    const [bomList, setBomList] = useState([]);
    const [pagination, setPagination] = useState({
        pageNum: 1,
        pageSize: 10,
        total: 0,
        totalPages: 0
    });
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    // 提取URL中的父级产品料号参数
    useEffect(() => {
        const getHashParams = () => {
            const hash = window.location.hash;
            const hashPath = hash.startsWith('#') ? hash.slice(1) : hash;
            const [, queryString] = hashPath.split('?');
            
            if (queryString) {
                const params = new URLSearchParams(queryString);
                const number = params.get('number');
                return number ? number.trim() : null;
            }
            return null;
        };

        const fetchedNumber = getHashParams();
        if (fetchedNumber) {
            setParentNumber(fetchedNumber);
        } else {
            setError('未找到产品料号参数');
            setLoading(false);
        }
    }, []);

    // 根据父级料号请求BOM数据
    const fetchBomData = async () => {
        if (!parentNumber) return;
        
        try {
            setLoading(true);
            // 调用后端POST接口，传递当前分页参数
            const result = await request('/admin/bom/getBom', {
                method: 'POST',
                body: {
                    parentNumber: parentNumber,
                    pageNum: pagination.pageNum,
                    pageSize: pagination.pageSize
                }
            });
            
            if (result.code === 200) {
                setBomList(result.data.list || []);
                setPagination(result.data.pagination || {
                    pageNum: 1,
                    pageSize: 10,
                    total: 0,
                    totalPages: 0
                });
                setError(null);
            } else {
                setError(result.msg || '获取BOM数据失败');
                setBomList([]);
                setPagination({
                    pageNum: 1,
                    pageSize: 10,
                    total: 0,
                    totalPages: 0
                });
            }
        } catch (err) {
            setError('网络错误，无法获取BOM数据');
            console.error('获取BOM数据出错:', err);
            setBomList([]);
        } finally {
            setLoading(false);
        }
    };

    // 初始加载和分页参数变化时重新获取数据
    useEffect(() => {
        fetchBomData();
    }, [parentNumber, pagination.pageNum, pagination.pageSize]);

    // 临时输出获取到的数据（用于调试）
    useEffect(() => {
        if (!loading && !error) {
            console.log('获取到的BOM数据:', {
                parentNumber,
                bomList,
                pagination
            });
        }
    }, [loading, error, parentNumber, bomList, pagination]);

    // 分页控制函数
    const handlePageChange = (newPage) => {
        if (newPage < 1 || newPage > pagination.totalPages) return;
        setPagination(prev => ({ ...prev, pageNum: newPage }));
    };

    // 每页条数变化
    const handlePageSizeChange = (e) => {
        const newSize = parseInt(e.target.value);
        setPagination(prev => ({ 
            ...prev, 
            pageSize: newSize,
            pageNum: 1 // 重置到第一页
        }));
    };

    return (
        <div style={{    
            height: "94%", 
            backgroundColor: `#F1F1F1`,
            right: "1%",
            top: "4vh",
            overflow: "auto", // 改为auto，允许滚动
            width: collapsed ? "94%" : "84%", 
            position: "absolute",  
            color: "white", 
            fontSize: "0.8rem"
        }}>
            <div style={styles.kshcontainer}>
                {/* 标题区域 */}
                <div style={styles.header}>
                    <h3>父级产品料号: {parentNumber || '加载中...'}</h3>
                    <div style={styles.summary}>
                        共 {pagination.total} 条记录，当前第 {pagination.pageNum}/{pagination.totalPages} 页
                    </div>
                </div>

                {/* 数据展示区域 */}
                <div style={styles.content}>
                    {loading ? (
                        <div style={styles.loading}>加载中...</div>
                    ) : error ? (
                        <div style={styles.error}>{error}</div>
                    ) : bomList.length === 0 ? (
                        <div style={styles.empty}>没有找到相关BOM数据</div>
                    ) : (
                        <>
                            {/* BOM表格 */}
                            <table style={styles.table}>
                                <thead>
                                    <tr style={styles.tableHeader}>
                                        <th style={styles.tableHeaderCell}>序号</th>
                                        <th style={styles.tableHeaderCell}>物料编号</th>
                                        <th style={styles.tableHeaderCell}>产品名称</th>
                                        <th style={styles.tableHeaderCell}>规格型号</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {bomList.map((item, index) => (
                                        <tr 
                                            key={item.id} 
                                            style={index % 2 === 0 ? styles.evenRow : styles.oddRow}
                                            onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#f0f7ff'}
                                            onMouseLeave={(e) => e.currentTarget.style.backgroundColor = index % 2 === 0 ? '#f9f9f9' : 'white'}
                                        >
                                            <td style={styles.tableCell}>{(pagination.pageNum - 1) * pagination.pageSize + index + 1}</td>
                                            <td style={styles.tableCell}>{item.number}</td>
                                            <td style={styles.tableCell}>{item.productName}</td>
                                            <td style={styles.tableCell}>{item.specificationAndModel}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>

                            {/* 分页控件 */}
                            <div style={styles.pagination}>
                                <div style={styles.pageSizeSelector}>
                                    每页显示:
                                    <select 
                                        value={pagination.pageSize} 
                                        onChange={handlePageSizeChange}
                                        style={styles.select}
                                    >
                                        <option value={5}>5条</option>
                                        <option value={10}>10条</option>
                                        <option value={20}>20条</option>
                                        <option value={50}>50条</option>
                                    </select>
                                </div>
                                
                                <div style={styles.pageButtons}>
                                    <button 
                                        style={styles.pageButton}
                                        onClick={() => handlePageChange(1)}
                                        disabled={pagination.pageNum === 1}
                                    >
                                        首页
                                    </button>
                                    <button 
                                        style={styles.pageButton}
                                        onClick={() => handlePageChange(pagination.pageNum - 1)}
                                        disabled={pagination.pageNum === 1}
                                    >
                                        上一页
                                    </button>
                                    
                                    <span style={styles.pageInfo}>
                                        第 {pagination.pageNum} 页 / 共 {pagination.totalPages} 页
                                    </span>
                                    
                                    <button 
                                        style={styles.pageButton}
                                        onClick={() => handlePageChange(pagination.pageNum + 1)}
                                        disabled={pagination.pageNum === pagination.totalPages}
                                    >
                                        下一页
                                    </button>
                                    <button 
                                        style={styles.pageButton}
                                        onClick={() => handlePageChange(pagination.totalPages)}
                                        disabled={pagination.pageNum === pagination.totalPages}
                                    >
                                        末页
                                    </button>
                                </div>
                            </div>
                        </>
                    )}
                </div>
            </div>
        </div>
    )
}

export default BomDetail

const styles = {
    kshcontainer: {
        width: "98%", 
        minHeight: "95%", 
        position: "absolute", 
        top: "3%", 
        left: "1%", 
        backgroundColor: "white", 
        color: "black",
        borderRadius: "10px",
        boxShadow: "0 2px 5px rgba(0,0,0,0.1)"
    },
    header: {
        padding: "1rem 2%",
        borderBottom: "1px solid #eee"
    },
    summary: {
        fontSize: "0.75rem",
        color: "#666",
        marginTop: "0.5rem"
    },
    content: {
        padding: "1rem 2%",
        minHeight: "300px"
    },
    loading: {
        textAlign: "center",
        padding: "3rem",
        color: "#666",
        fontSize: "0.9rem"
    },
    error: {
        textAlign: "center",
        padding: "3rem",
        color: "#dc3545",
        fontSize: "0.9rem"
    },
    empty: {
        textAlign: "center",
        padding: "3rem",
        color: "#666",
        fontSize: "0.9rem"
    },
    table: {
        width: "100%",
        borderCollapse: "collapse",
        fontSize: "0.75rem"
    },
    tableHeader: {
        backgroundColor: "#f2f2f2"
    },
    tableHeaderCell: {
        padding: "0.7rem",
        textAlign: "left",
        borderBottom: "1px solid #ddd",
        fontWeight: "bold"
    },
    tableCell: {
        padding: "0.7rem",
        borderBottom: "1px solid #eee",
        wordBreak: "break-all"
    },
    evenRow: {
        backgroundColor: "#f9f9f9"
    },
    oddRow: {
        backgroundColor: "white"
    },
    pagination: {
        marginTop: "1.5rem",
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        fontSize: "0.75rem"
    },
    pageSizeSelector: {
        display: "flex",
        alignItems: "center",
        gap: "0.5rem"
    },
    select: {
        padding: "0.2rem 0.4rem",
        border: "1px solid #ddd",
        borderRadius: "3px",
        fontSize: "0.75rem"
    },
    pageButtons: {
        display: "flex",
        alignItems: "center",
        gap: "0.5rem"
    },
    pageButton: {
        padding: "0.2rem 0.8rem",
        border: "1px solid #ddd",
        borderRadius: "3px",
        backgroundColor: "white",
        cursor: "pointer",
        fontSize: "0.75rem"
    },
    pageInfo: {
        padding: "0 0.5rem"
    }
}
    